<template>
  <view class="viewport">
    <view class="logo">
      <image src="/static/images/logo.png"></image>
    </view>
    <view class="forget-password">
      <uni-forms :model="forgetForm" ref="forgetFormRef" :rules="forgetFormRules">
        <!-- 邮箱输入框 -->
        <uni-forms-item name="email">
          <uni-easyinput
            type="text"
            v-model="forgetForm.email"
            placeholder="请输入注册邮箱"
          ></uni-easyinput>
        </uni-forms-item>

        <!-- 验证码输入框 -->
        <uni-forms-item name="code">
          <uni-easyinput
            v-model="forgetForm.code"
            placeholder="请输入验证码"
          >
            <template #right>
              <button
                class="code-btn"
                :disabled="countdown > 0"
                @tap="getResetCode"
              >
                {{ countdown > 0 ? countdown + "秒后重发" : "获取验证码" }}
              </button>
            </template>
          </uni-easyinput>
        </uni-forms-item>

        <!-- 新密码输入框 -->
        <uni-forms-item name="newPassword">
          <uni-easyinput
            type="password"
            v-model="forgetForm.password"
            placeholder="请输入新密码"
          ></uni-easyinput>
        </uni-forms-item>

        <!-- 提交按钮 -->
        <button @tap="onSubmit" class="button">提交</button>
      </uni-forms>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { resetPasswordByEmailAPI, getEmailCodeAPI } from "@/api/forget"; // 导入相应的 API
import type { ResetPasswordByEmailParams } from "@/types/forget";

const countdown = ref(0);
let timer = null; 

// 重置密码表单的数据
const forgetForm = reactive<ResetPasswordByEmailParams>({
  email: "",
  code: "",
  password: "",
});

// 表单校验规则
const forgetFormRef = ref();

const forgetFormRules = {
  email: [
    { required: true, message: "请输入邮箱" },
    { type: "email", message: "请输入正确的邮箱格式" }
  ],
  code: [
    { required: true, message: "请输入验证码" },
    { length: 4, message: "验证码长度为4位" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码" },
    { min: 8, message: "密码长度至少为8位" }
  ]
};

// 发送验证码请求
const getResetCode = async () => {
  try {
    await forgetFormRef.value?.validateField?.("email");
    setTimer(); // 启动计时器
    const res = await getEmailCodeAPI({
      email: forgetForm.email,
      type: "reset_password", 
    });
    
    if (res && res.success) {
      uni.showToast({
        icon: "none",
        title: "验证码已发送，请注意查收",
      });
    } else {
      uni.showToast({
        icon: "none",
        title: "发送验证码失败，请重试",
      });
    }
  } catch (error) {
    console.error("发送验证码请求失败：", error);
    uni.showToast({
      icon: "none",
      title: "请求失败，请检查网络或联系支持",
    });
  }
};

// 设置验证码倒计时
const setTimer = () => {
  clearInterval(timer); // 清除之前的定时器
  countdown.value = 60;
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

// 提交表单，调用重置密码 API
const onSubmit = async () => {
  try {
    await forgetFormRef.value?.validate();
    const res = await resetPasswordByEmailAPI(forgetForm);
    if (res && res.success) {
      uni.showToast({ title: "密码重置成功", icon: "success" });
      uni.navigateBack(); // 跳转回登录页面
    } else {
      // 特定错误处理：用户不存在
      if (res.data && res.data.code === "-1" && res.data.message === "用户不存在") {
        uni.showToast({
          title: "用户不存在，请检查您输入的邮箱是否正确",
          icon: "none",
        });
      } else {
        uni.showToast({
          title: res.message || "密码重置失败",
          icon: "none",
        });
      }
    }
  } catch (error) {
    console.error("重置密码请求失败：", error);
    const errorMessage = error?.response?.data?.message || "请求失败，请检查网络或联系支持";
    uni.showToast({ title: errorMessage, icon: "none" });
  }
};
</script>

<style lang="scss">
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
}

.forget-password {
  height: 60vh;
  padding: 40rpx 20rpx;

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 8rpx;
    color: #fff;
    background-color: #28bb9c;
  }

  .code-btn {
    line-height: 78rpx;
    font-size: 28rpx;
    color: #333;
  }
}

.logo {
  flex: 1;
  text-align: center;
  image {
    width: 220rpx;
    height: 220rpx;
    margin-top: 12vh;
  }
}
</style>